"""
系统日志表结构升级脚本
添加新的日志字段以支持更详细的日志记录
"""

from alembic import op
import sqlalchemy as sa
from sqlalchemy import text

def upgrade():
    """升级数据库结构"""
    
    # 检查表是否存在
    connection = op.get_bind()
    inspector = sa.inspect(connection)
    
    if 'system_logs' not in inspector.get_table_names():
        print("system_logs表不存在，跳过升级")
        return
    
    # 获取现有列
    existing_columns = [col['name'] for col in inspector.get_columns('system_logs')]
    
    # 需要添加的新字段
    new_columns = [
        ('action', sa.String(100), True),  # (字段名, 类型, 是否可为空)
        ('resource_type', sa.String(50), True),
        ('resource_id', sa.String(100), True),
        ('session_id', sa.String(100), True),
        ('execution_time', sa.Float, True),
        ('status_code', sa.Integer, True),
        ('request_id', sa.String(100), True),
        ('parent_log_id', sa.Integer, True),
        ('tags', sa.Text, True),
        ('severity', sa.Integer, True),
        ('request_method', sa.String(10), True),
        ('request_url', sa.Text, True),
        ('response_size', sa.Integer, True),
        ('error_code', sa.String(50), True),
        ('stack_trace', sa.Text, True)
    ]
    
    # 添加不存在的字段
    for column_name, column_type, nullable in new_columns:
        if column_name not in existing_columns:
            print(f"添加字段: {column_name}")
            try:
                with op.batch_alter_table('system_logs') as batch_op:
                    batch_op.add_column(sa.Column(column_name, column_type, nullable=nullable))
                    
                    # 为某些字段添加索引
                    if column_name in ['action', 'resource_type', 'resource_id', 'session_id', 'request_id']:
                        batch_op.create_index(f'ix_system_logs_{column_name}', [column_name])
                        
            except Exception as e:
                print(f"添加字段 {column_name} 失败: {e}")
        else:
            print(f"字段 {column_name} 已存在，跳过")
    
    # 添加外键约束（如果不存在）
    try:
        existing_fks = [fk['name'] for fk in inspector.get_foreign_keys('system_logs')]
        
        if 'fk_system_logs_parent_log_id' not in existing_fks:
            with op.batch_alter_table('system_logs') as batch_op:
                batch_op.create_foreign_key(
                    'fk_system_logs_parent_log_id',
                    'system_logs',
                    ['parent_log_id'],
                    ['id']
                )
                print("添加parent_log_id外键约束")
    except Exception as e:
        print(f"添加外键约束失败: {e}")
    
    # 设置severity字段的默认值
    try:
        connection.execute(text("UPDATE system_logs SET severity = 0 WHERE severity IS NULL"))
        print("设置severity字段默认值")
    except Exception as e:
        print(f"设置默认值失败: {e}")

def downgrade():
    """降级数据库结构"""
    
    # 删除添加的字段（谨慎操作）
    fields_to_remove = [
        'action', 'resource_type', 'resource_id', 'session_id',
        'execution_time', 'status_code', 'request_id', 'parent_log_id',
        'tags', 'severity', 'request_method', 'request_url',
        'response_size', 'error_code', 'stack_trace'
    ]
    
    try:
        with op.batch_alter_table('system_logs') as batch_op:
            # 删除外键约束
            try:
                batch_op.drop_constraint('fk_system_logs_parent_log_id', type_='foreignkey')
            except:
                pass
            
            # 删除索引
            for field in ['action', 'resource_type', 'resource_id', 'session_id', 'request_id']:
                try:
                    batch_op.drop_index(f'ix_system_logs_{field}')
                except:
                    pass
            
            # 删除字段
            for field in fields_to_remove:
                try:
                    batch_op.drop_column(field)
                    print(f"删除字段: {field}")
                except Exception as e:
                    print(f"删除字段 {field} 失败: {e}")
                    
    except Exception as e:
        print(f"降级失败: {e}")

if __name__ == "__main__":
    # 可以直接运行此脚本进行升级
    print("开始升级系统日志表结构...")
    upgrade()
    print("升级完成")